<template>
  <div style="width:80%;margin:0 auto;padding:20px 0">
    <h2>发布申请单</h2>
    <!-- <el-card class="box-card" style="width:90%;margin:0px auto;padding-top:20px"> -->
      <el-row class="mb8" ref="refbut" v-if="istype == '1'">
      <el-col :span="24">
        <el-dropdown style="margin: 2% 4%" @command="(command) => handleCommand(command)"
          v-hasPermi="['archive:fileCollection:preArchiving:download']">
          <el-button type="primary" plain>
            下载<i class="el-icon-arrow-down el-icon--right"></i>
          </el-button>
          <el-dropdown-menu slot="dropdown">
            <el-dropdown-item command="archiveTransfer">审计档案移交清单</el-dropdown-item>
            <el-dropdown-item command="photoHandover">照片及录音录像移交清单</el-dropdown-item>
            <el-dropdown-item command="projectHandover">工程档案移交清单</el-dropdown-item>
          </el-dropdown-menu>
        </el-dropdown>
      </el-col>
    </el-row>
    <el-row ref="queryForm">
      <el-col :span="24">
        <el-form ref="form" :model="form" label-width="120px">
          <el-row>
            <el-col :span="11" :xs="24">
              <el-form-item label="">
                <span slot="label">
                  <em style="color:red"> * </em>
                  申请人
                </span>
                <treeselect v-model="form.submitUserId" :options="deptUserOptions" :normalizer="normalizer"
                  noResultsText="暂无数据" placeholder="请选择申请人" :disable-branch-nodes="true"
                  :disabled="istype == '3' || istype == '2' || istype == '0'" />
              </el-form-item>
            </el-col>
            <el-col :span="11" :xs="24">
              <el-form-item label="归属部门" prop="submitDeptId">
                <span slot="label">
                  <em style="color:red"> * </em>
                  归属部门
                </span>
                <treeselect v-model="form.submitDeptId" :options="deptOptions" noResultsText="暂无数据" placeholder="请选择归属部门"
                  :disabled="istype == '3' || istype == '2' || istype == '0'" />
              </el-form-item>
            </el-col>
          </el-row>
          
          <el-row>
            <el-col :span="11" :xs="24">
              <el-form-item label="" prop="fanganName">
                <span slot="label">
                  <em style="color:red"> * </em>
                  方案名称
                </span>
                <el-input v-model="form.fanganName" placeholder="请输入方案名称" :disabled="istype == '3' || istype == '2' || istype == '0'"></el-input>
              </el-form-item>
            </el-col>
            <el-col :span="11" :xs="24">
              <el-form-item label="" prop="mubiaoXitong">
                <span slot="label">
                  <em style="color:red"> * </em>
                  目标系统
                </span>
                <el-input v-model="form.mubiaoXitong" disabled></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11" :xs="24">
              <el-form-item label="" prop="fabuFangshi">
                <span slot="label">
                  <em style="color:red"> * </em>
                  发布方式
                </span>
                <el-select v-model="form.fabuFangshi" placeholder="请选择发布方式" style="width:100%;" :disabled="istype == '3' || istype == '2' || istype == '0'">
                    <el-option v-for="(i, idx) in dict.type.FABUFANGSHI" :key="idx" :label="i.label"
                        :value="i.value"></el-option>

                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="11" :xs="24">
              <el-form-item label="" prop="categoryId">
                <span slot="label">
                  <em style="color:red"> * </em>
                  档案类型
                </span>
                <el-input v-model="form.categoryName" disabled></el-input>
                <!-- <el-select :disabled="istype == '3' || istype == '2' || istype == '0'" v-model="form.categoryId" placeholder="请选择档案类型" style="width:100%">
                    <el-option v-for="item in deptOptions" :key="item.id" :label="item.label" :value="item.id">
                    </el-option>
                </el-select> -->
             
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="11" :xs="24">
              <el-form-item label="">
                <span slot="label">
                  <em style="color:red"> * </em>
                  发布网段
                </span>

                <el-select v-model="form.fabuWangduan" placeholder="请选择发布网段" style="width:100%;" :disabled="istype == '3' || istype == '2' || istype == '0'" >
                    <el-option v-for="(i, idx) in dict.type.FABUWANGDUAN" :key="idx" :label="i.label"
                        :value="i.value"></el-option>
                </el-select>
           
              </el-form-item>
            </el-col>
            <el-col :span="11" :xs="24">
              <el-form-item label="" prop="fabuType">
                <span slot="label">
                  <em style="color:red"> * </em>
                  发布内容
                </span>
                <el-select v-model="form.fabuType" placeholder="请选择发布内容" style="width:100%;"  :disabled="istype == '3' || istype == '2' || istype == '0'" >
                    <el-option v-for="(i, idx) in dict.type.FABUTYPE" :key="idx" :label="i.label"
                        :value="i.value"></el-option>
                </el-select>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="22" :xs="24">
              <el-form-item label="申请日期">
                <el-input v-model="form.submitTime" readonly class="input-border"
                  :disabled="istype == '3' || istype == '2' || istype == '0'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="22" :xs="24">
              <el-form-item label="发布说明">
                <el-input  type="textarea" v-model="form.fabuShuoming" readonly class="input-border"
                  :disabled="istype == '3' || istype == '2' || istype == '0'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <el-row class="mb8" ref="refbut" style="width:90%;margin:0 auto">
      <el-col :span="1.5">
        <el-button type="danger" plain icon="el-icon-delete" @click="delTap" v-if="istype == '1'">移除</el-button>
      </el-col>
    </el-row>
    <div class="tableData">
      <el-table :data="tableDataList" @selection-change="handleSelectionChange" border align="center"
        header-align="center" :loading="loading" @cell-dblclick="celldblclick" :row-key="getRowKeys" lazy :load="load"
        :tree-props="{ children: 'children', hasChildren: 'hasChildren' }" style="width: 96%" >
        <el-table-column type="selection" width="55" align="center" prop="daId" :selectable="checkboxSelect" :reserve-selection="true">
        </el-table-column>
     <el-table-column prop="date" label="档案类型">
                <template slot-scope="scope">
                    {{ scope.row.categoryName }}
                </template>
            </el-table-column>
            <el-table-column prop="dh" label="档号" width="300">
            </el-table-column>
            <el-table-column prop="zrz" label="责任者">
            </el-table-column>
            <el-table-column prop="title" label="题名">
            </el-table-column>
            <el-table-column prop="rq" label="日期">
            </el-table-column>
            <el-table-column prop="ys" label="页数">
            </el-table-column>
            <el-table-column prop="isOpens" label="开放属性">
                <template slot-scope="scope">
                    <span v-for="(i, idx) in dict.type.IS_OPENS" :key="idx">
                        {{ scope.row.isOpens == i.value ? i.label : '' }}
                    </span>
                </template>
            </el-table-column> 
            <el-table-column prop="bz" label="备注"/>
      </el-table>
      <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="selectDataOfFanganList" /> 
    </div>
    <!-- </el-card> -->

    <el-row style="width:90%;margin-top:20px" ref="queryForm" v-show="isShowInfo && istype != '0'">
      <el-col :span="24">
        <el-form ref="form" :model="form" label-width="120px">
          <el-row>
            <el-col :span="18">
              <el-form-item label="">
                <span slot="label">
                  <em style="color:red"> * </em>
                  审批意见：
                </span>
                <el-radio-group v-model="form.resource" :disabled="istype == '3'"
                  @change="chanageAllStatus(form.resource)">
                  <el-radio :label="1">全部同意</el-radio>
                  <el-radio :label="0">全部不同意</el-radio>
                  <!-- <el-radio :label="2">自定义</el-radio> -->
                </el-radio-group>
              </el-form-item>
              <el-form-item label="" v-hasPermi="['archive:preArchiveApproval:nextAssignee']"
                v-show="isShowApprover && istype != '3'">
                <span slot="label">
                  <em style="color:red"> * </em>
                  下一节点审批人
                </span>
                <treeselect v-model="form.nextAssignee" :options="roleUserOptions" :normalizer="normalizer"
                  noResultsText="暂无数据" placeholder="请选择审批人" :disable-branch-nodes="true" :disabled="istype == '3'" />
              </el-form-item>
              <el-form-item label="" v-hasPermi="['archive:preArchiveApproval:completion']" v-show="istype != '3'">
                <el-checkbox v-model="form.endProcess" :disabled="istype == '3'">办结流程</el-checkbox>
              </el-form-item>
            </el-col>
          </el-row>
          <el-row>
            <el-col :span="24">
              <el-form-item label="批 注：">
                <el-input v-model="form.note" type="textarea" :rows="3" :disabled="istype == '3'"></el-input>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
      </el-col>
    </el-row>
    <el-row>
      <el-col :span="24" class="j_content margin_top">
        <el-button type="primary" size="medium  " @click="handleSubmit" :disabled="istype == '3'"
          v-show="istype != '0'">提交</el-button>
        <!--                <el-button size="medium">取消</el-button>-->
      </el-col>
    </el-row>

    <!--start  组件详情 -->
    <jianDetailsOpen v-if="jianDetailsOpen" :open="jianDetailsOpen" :celldbData="celldbData"
      @detailsHandleClose="detailsHandleClose">
    </jianDetailsOpen>
    <!--end 组件详情 -->
    <!-- start 组卷\项目详情 -->
    <juanDetailsOpen v-if="juanDetailsOpen" :open="juanDetailsOpen" :celldbData="celldbData"
      @detailsHandleClose="detailsHandleClose"></juanDetailsOpen>
    <!-- end 组卷\项目详情 -->

  </div>
</template>
<script>
import { deptTreeNoDateScope } from "@/api/system/user";
import estimateTableHeight from '@/mixins/estimateTableHeight'//vue项目中element-tabel自动计算高度
import {
  getArchiveList,
  delArchiveFormSave,
  submit,
  deptUserTree,
  roleUserTree,
  formDataSave, getArchiveInfo,
  getthbytreenodeHeaderList, setArchiveProcessStatusByArchiveId, getdetectionSchemeList, detection, listinfo, changeAllArchiveState
} from "@/api/archive/fileCollection/preArchiving.js" //档案整理接口
import Treeselect from "@riophae/vue-treeselect";
import "@riophae/vue-treeselect/dist/vue-treeselect.css";
import jianDetailsOpen from '@/components/componentsJianDetails/index.vue' //件详情
import juanDetailsOpen from '@/components/componentsJuanDetails/index.vue' //卷详情
import { getInfo } from "@/api/login";
import { getLastIndexOf } from "@/utils";
import PlanDetail from "@/views/archive/fourNatures/detectionPlan/planDetail";
import { selectDataOfFangan } from "@/api/archive/filesManage/editReleaseManage.js"
export default {
  props: ["istype", "isShow", "roleUserList"],// <!--归档申请单 istype="1"   待办 istype="2"  已办istype="3" -->
  mixins: [estimateTableHeight], // 混入方法
  archive_Dicts: ['FABUFANGSHI', 'FABUWANGDUAN', 'FABUTYPE','IS_OPENS'],
  components: { Treeselect, jianDetailsOpen, juanDetailsOpen, PlanDetail },
  data() {
    return {
      form: {},
      tableDataList: [],//申请单列表
      loading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      total:0,
      // 部门树选项
      deptOptions: [],
      // 人员树选项
      deptUserOptions: [],
      roleUserOptions: [],
      submitTime: "",
      isShowInfo: false,
      taskId: '',
      cloumnApproval: false,
      jianDetailsOpen: false,//件详情弹窗
      juanDetailsOpen: false,//卷详情弹窗
      // 获取row的key值
      getRowKeys(row) {
        return row.daId;
      },
      // 要展开的行，数值的元素是row的key值
      expands: [],
      height: '',
      // 流程id
      processId: '',
      info: '',
      flag: true,

      sxjcType: undefined,
      sxjcList: [],
      dialogVisible: false, //检测方案弹窗

      // 方案明细弹窗
      planOpen: false,
      planTitle: '检测详情',
      chooseNextAssignee: false,
      chooseNextAssigneeByRoleKey: false,

      // 是否出现审批人
      isShowApprover: false,
      fanganId:""
    }
  },
  created() {
    this.getDeptTreePost(); //归属部门树接口
    this.deptUserTreePost();//获取人员树接口

    this.getArchiveList(); //申请单列表
    if (this.istype == '1') {
      this.height = '20vh'
      // 当前登录人
      getInfo().then(res => {
        this.$set(this.form, 'submitUserId', res.user.userId)
        this.$set(this.form, 'submitDeptId', res.user.deptId)
      })
    }
    //当前时间
    const date = new Date()
    const year = date.getFullYear()
    const month = ('0' + (date.getMonth() + 1)).slice(-2)
    const day = ('0' + date.getDate()).slice(-2)
    this.form.submitTime = year + "-" + month + "-" + day;
    console.log(this.form.submitTime,"sdklfjlsdkjkl")

    if (this.isShow == "true") {
      this.isShowInfo = true
    } else {
      this.isShowInfo = false
    }
  },
  filters: {
    formattedTime(value) {
      // 格式化日期，你可以使用任何适合你的格式
      const date = new Date(value);
      return date.toLocaleDateString(); // 返回格式化后的日期字符串
    },
  },
  methods: {
    init(val) {
      console.log(val,val.processVariables.id,"ksjfklsdjfkldsjfkl")
      this.info = val
      this.taskId = val.id
      this.processId = val.instanceId
      this.form = {}
      const menuId = this.$route.meta.menuId
      this.tableDataList = []
      this.isShowApprover = false
      this.fanganId=val.processVariables.id
      this.queryParams["fanganId"] =val.processVariables.id
    
      // if (val.archiveVariables.length != 0) {
      //   this.tableDataList = val.archiveVariables
      //   for (let i = 0; i < val.archiveVariables.length; i++) {
      //     this.tableDataList[i].hasChildren = true
      //   }
      // }
      this.selectDataOfFanganList(val.processVariables.id)
      if (val.processVariables != null) {
        this.form.submitUserId = val.processVariables.submitUserId;
        this.form.submitDeptId = val.processVariables.submitDeptId;
        this.form.fanganName=val.processVariables.fanganName;
        this.form.mubiaoXitong=val.processVariables.mubiaoXitong;
        this.form.fabuFangshi=val.processVariables.fabuFangshi;
        this.form.categoryName=val.processVariables.categoryName;
        this.form.fabuWangduan=val.processVariables.fabuWangduan;
        this.form.fabuType=val.processVariables.fabuType;
        this.form.fabuShuoming=val.processVariables.fabuShuoming;
        this.form.submitTime=val.processVariables.shenqingTime;
        // if (val.processVariables.submitTime != undefined) {
        //   this.form.submitTime = this.processingTime(val.processVariables.submitTime * 1);
        // }
      }
      if (val.otherVariables != null) {
        getInfo().then(res => {
          const userName = res.user.userName
          var arr = val.otherVariables.activitList.filter(item => item.assignee == userName)
          if (arr.length > 0) {
            if (arr[0].isAgree.controlValue == '同意') {
              this.$set(this.form, 'resource', 1)
            } else {
              this.$set(this.form, 'resource', 0)
            }
            console.log(this.form,"liuhaiorng")
          
            if (arr[0].comment != null || arr[0].comment != undefined) {
              this.$set(this.form, 'note', arr[0].comment.controlValue)
            }
          }
        })
      }
      this.getConfigKey("NEXT_ASSIGNEE_ROLE_KEY").then(response => {
        if (response.msg == '') {
          this.chooseNextAssignee = false
        } else {
          this.chooseNextAssignee = true
        }
      });
      this.getConfigKey("NEXT_ASSIGNEE_BY_ROLE_KEY").then(response => {  //是否指定下一节点审批人（预选角色下的人）
        if (response.msg == 'true') {
          this.chooseNextAssigneeByRoleKey = true
         
        } else {
          this.chooseNextAssigneeByRoleKey = false
          this.roleUserTreePost();//获取人员树接口
         
        }
      });
    },

    //获取审批档案列表
    selectDataOfFanganList(){
      
      selectDataOfFangan(this.queryParams).then(res=>{
        this.total=res.total
        this.tableDataList = res.rows;
      })
    },
    processingTime(time) {
      const date = new Date(time);
      // 获取日期的年、月、日
      const year = date.getFullYear();
      const month = String(date.getMonth() + 1).padStart(2, '0'); // 月份从0开始，需要加1
      const day = String(date.getDate()).padStart(2, '0');
      // 获取时间的小时、分钟、秒
      // const hours = String(date.getHours()).padStart(2, '0');
      // const minutes = String(date.getMinutes()).padStart(2, '0');
      // const seconds = String(date.getSeconds()).padStart(2, '0');
      // 构建日期时间字符串
      return `${year}-${month}-${day}`;
    },
    chanageAllStatus(resource) {
      if (this.chooseNextAssigneeByRoleKey && resource == '1') {
        let agreeUserList = this.roleUserList.agreeUserList
        this.roleUserOptions = agreeUserList
      } else if (this.chooseNextAssigneeByRoleKey && resource == '0') {
        let notAgreeUserList = this.roleUserList.notAgreeUserList
        this.roleUserOptions = notAgreeUserList
      } else if (this.chooseNextAssigneeByRoleKey && resource == '2') {
        let otherUserList = this.roleUserList.otherUserList
        this.roleUserOptions = otherUserList
      }
      console.log( this.roleUserOptions,"ksldjflsdkjfkljds")
      if (this.roleUserOptions == undefined || this.roleUserOptions.length == 0) {
        this.isShowApprover = false
      } else {
        this.isShowApprover = true
      }
      if (resource == '0' || resource == '1') {
        this.cloumnApproval = true;

        //TODO 新建接口批量修改
        changeAllArchiveState(this.processId, resource).then(resp => {
          for (let i = 0; i < this.tableDataList.length; i++) {
            if (this.tableDataList[i].archiveAgreeStatusCanEdit != 0) {
              this.tableDataList[i].archiveAgreeStatus = resource + '';
            }
          }
          //this.init(this.info)
          this.form.resource = resource;
          this.$forceUpdate();
        })
      } else if (resource == '2') {
        this.cloumnApproval = false;
        this.form.resource = resource;
        this.$forceUpdate();
      }

    },
    formattedTime(value) {
      // 格式化日期，你可以使用任何适合你的格式
      const date = new Date(value);
      return date.toLocaleDateString(); // 返回格式化后的日期字符串
    },
    /** 查询部门下拉树结构 */
    getDeptTreePost() {
      deptTreeNoDateScope().then(response => {
        this.deptOptions = response.data;
      });
    },
    /**获取人员树接口 */
    deptUserTreePost() {
      deptUserTree().then(response => {
        this.deptUserOptions = response.data;
        // 重命名树结构中的字段
        this.deptUserOptions.forEach(node => {
          this.appendUser(node);
        });
        console.log(this.deptUserOptions)
      });
     
     
    },


    //下一审批人列表
    roleUserTreePost(){
      if (this.istype == '2') {
        roleUserTree().then(response => {
          
          this.roleUserOptions = response.data;
          console.log(this.roleUserOptions,"----------------------------------")
          if(this.roleUserOptions!=undefined){
          // 重命名树结构中的字段
          this.roleUserOptions.forEach(node => {
            this.appendUser(node);
          });
        }
        });
      }
    },
    appendUser(node) {
      if (node.children && node.children.length > 0) {
        node.children.forEach(child => {
          this.appendUser(child);
        });
      }
      if (node.userChildren && node.userChildren.length > 0) {
        node.userChildren.forEach(user => {
          user.nodeType = 'user'; // 添加 nodeType 属性
        });
        node.children = [...(node.children || []), ...node.userChildren];
        delete node.userChildren;
      }
    },
    normalizer(node) {
      // console.log(node)
      // console.log(node.children,"++111111111111111++")
      if (node.nodeType != 'user') {
        if (node.children == undefined) {
          node["children"] = undefined
          node['isDisabled'] = true;
        }
      }
      //去掉children=[]的children属性
      // if (node.children && !node.children.length) {
      //     delete node.children;
      // }
      // if (node.isLeaf == 'Y' && node.typeLevel != 3) {
      //     node['isDisabled'] = true;
      // }
      // return {
      //     id: node.typeId,
      //     label: node.typeName,
      //     children: node.children,
      // }
    },

    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.daId);
      this.single = selection.length != 1;
      this.multiple = !selection.length;
      console.log(this.ids,"ll")
    },
    getArchiveList() {
      this.loading = true;
      getArchiveList().then(res => {
        this.loading = false;
        const menuId = this.$route.meta.menuId
        if (res.code == "200" && this.istype == "1" && res.data != undefined) {
          this.tableDataList = res.data;
          for (let i = 0; i < res.data.length; i++) {
            this.tableDataList[i].hasChildren = true
          }
        }
      })
    },
    // 懒加载表格数据
    load(tree, treeNode, resolve) {
      console.log(123)
      setTimeout(() => {
        var level = "";
        if (getLastIndexOf(tree.SUB_TABLE_NAME) == "F") {  //F 件
          level = 'efile'
        } else if (getLastIndexOf(tree.SUB_TABLE_NAME) == "V") { //卷
          level = 'jian'
        } else { //项目
          level = 'juan'
        }
        const menuId = this.$route.meta.menuId
        const archiveId = tree.ID
        const categoryId = tree.CATEGORY_ID
        if (level != 'efile') {
          getArchiveInfo(
            {
              menuId: menuId, level: level, archiveId: archiveId, categoryId: categoryId
            }
          ).then(response => {
            for (let i = 0; i < response.rows.length; i++) {
              response.rows[i].hasChildren = true
              response.rows[i].isChildren = '1'
            }
            resolve(response.rows)
          })
        } else {
          resolve([])
        }
      }, 1000)
    },
    // 是否禁用多选框
    checkboxSelect(row) {
      if (row.isChildren == '1') {
        return false
      } else {
        return true
      }
    },
    delTap() {
      // console.log(this.multiple, this.single, ")))")
      if (this.multiple) {
        this.$message({ message: '请选择要移除的数据哦', type: 'warning' })
      } else {
        this.$modal.confirm('是否确认删除所选数据项？').then(() => {
          delArchiveFormSave(this.ids).then(res => {
            this.$modal.msgSuccess("删除成功");
            this.tableDataList = []
            this.getArchiveList();
          })
        }).catch(() => { });

      }
    },
    //提交
    handleSubmit() {
    
      
      const personnel = this.findNodeById(this.form.submitUserId, this.deptUserOptions);
      if (personnel) {
        this.form.submitUser = personnel.label
      }
      console.log(this.form.submitDeptId, this.deptOptions,"klsdfjklsdjfkldsjfklsdjf")
      // 获取部门
      const department = this.findNodeById(this.form.submitDeptId, this.deptOptions)
      console.log(department,"00")
      if (department) {
        this.form.submitDept = department.label
      }
   
      if (personnel == undefined || personnel == null || personnel == "") {
        this.$modal.msgError("申请人不能为空");
        return;
      } else if (department == undefined || department == null || department == "") {
        this.$modal.msgError("归属部门不能为空");
        return;
      } else if (this.tableDataList.length == 0) {
        this.$modal.msgError("档案数据不能为空");
        return;
      }
      if (this.chooseNextAssignee && !this.form.endProcess && this.isShowApprover) {
        if (this.form.nextAssignee == undefined || this.form.nextAssignee == null || this.form.nextAssignee == '') {
          this.$modal.msgError("请选择下一审批人");
          return;
        }
      }
      // this.planOpen = false
      let agreeFlag = true;
      let notAgreeFlag = true;
      let controlVal = 1;
      if (this.form.resource == '2') {
        for (let i = 0; i < this.tableDataList.length; i++) {
          if (this.tableDataList[i].archiveAgreeStatus == undefined || this.tableDataList[i].archiveAgreeStatus == '') {
            this.$modal.msgWarning('请为所有数据选择审批意见')
            return;
          } else {
            agreeFlag = this.tableDataList[i].archiveAgreeStatus == '1' && agreeFlag ? agreeFlag : false;
            notAgreeFlag = this.tableDataList[i].archiveAgreeStatus == '0' && notAgreeFlag ? notAgreeFlag : false;
          }
        }
        controlVal = agreeFlag ? 1 : notAgreeFlag ? 0 : 1;
      } else {
        controlVal = this.form.resource;
      }


      //  <!--归档申请单 istype="1"   待办 istype="2"  已办istype="3" -->
      if (this.istype == "1") {
        console.log(this.form)
        submit(this.form).then(res => {
          this.$modal.msgSuccess(res.msg)
          this.tableDataList = []
          this.form = {
            submitUserId: undefined,
            submitDeptId: undefined,
            remark: undefined
          }
          const date = new Date()
          const year = date.getFullYear()
          const month = ('0' + (date.getMonth() + 1)).slice(-2)
          const day = ('0' + date.getDate()).slice(-2)
          this.form.submitTime = year + "-" + month + "-" + day;
          this.getArchiveList()
          if (res.data.length > 0) {
            const currentPath = this.$route.path;
            const parts = currentPath.split('/');
            const lastPart = parts[parts.length - 1];
            const jumpAddress = currentPath.replace(lastPart, 'notQrocessed');
            this.$router.push({
              path: jumpAddress,
              query: {
                taskId: res.data[0]
              },
            });
          }
        })
      } else if (this.istype == '2') {
        if (this.form.resource == null || this.form.resource == undefined) {
          this.$modal.msgWarning('请选择审批意见')
          return;
        }
        var data = []
        if (this.form.endProcess == true) {
          controlVal = 2;
        }
        data = [{
          controlId: 'is_agree',
          controlDefault: '不同意--__--同意--__--办结',
          controlIsParam: 'i',
          controlLable: '审批意见',
          controlType: 'radio',
          controlValue: controlVal
        }, {
          controlId: "comment",
          controlDefault: 'FormProperty_2ugo1se',
          controlIsParam: 'f--!!null',
          controlLable: '批注',
          controlType: 'textarea',
          controlValue: this.form.note
        }, {
          controlId: "nextAssignee",
          controlDefault: 'FormProperty_298545',
          controlIsParam: 'f--!!null',
          controlLable: '下一节点办理人',
          controlType: 'input',
          controlValue: this.form.nextAssignee
        }];
        data.id = this.taskId
        formDataSave(data).then(response => {
          this.$modal.msgSuccess(response.msg)
          this.$emit('close')
        })
        this.$emit('close')
      }
    },
    handlecloseDelDialog() {
      // this.$modal.closeLoading();
      this.dialogVisible = false;
    },
    findNodeById(id, nodes) {
      console.log(id,nodes)
      for (const node of nodes) {

        // console.log(node.id,id,typeof(node.id),typeof(toString(id)),node.id === id,"2222")
        if (node.id == id) {
          // console.log(typeof(node.id),typeof(toString(id)),node.id === id,"=============")
          return node;
        }
         if (node.children) {
          const result = this.findNodeById(id, node.children);
          if (result) {
            return result;
          }
         }
      }
      return null;
    },
    //关闭详情页面
    detailsHandleClose() {
      this.jianDetailsOpen = false;
      this.juanDetailsOpen = false;
    },
    celldblclick(row) {
      console.log(row, '------------------')
      var label = "";
      var level = "";
      if (getLastIndexOf(row.SUB_TABLE_NAME) == "F") {  //F 件
        level = 0
        label = row.TITLE;
      } else if (getLastIndexOf(row.SUB_TABLE_NAME) == "V") { //卷
        level = 1
        label = row.TITLE;
      } else { //项目
        level = 3
        label = row.XMMC;
      }
      const menuId = this.$route.meta.menuId
      getthbytreenodeHeaderList(
        {
          categoryId: row.CATEGORY_ID, menuId: menuId, subTableName: row.SUB_TABLE_NAME
        }
      ).then(response => {
        var tableHeaderList = response.rows
        this.celldbData = {
          id: row.ID,
          categoryId: row.CATEGORY_ID,
          menuId: menuId,
          sub_table_name: row.SUB_TABLE_NAME,
          label: label,
          level: level,
          ifSub_table_name: row.SUB_TABLE_NAME,
          isDel: "0",  //判断是回收站数据还是接收收据 isDel:1  回收站    isDel:0 //离线接收、档案接收、在线接收
          tableHeaderList: tableHeaderList
        }
        this.$nextTick(() => {
          if (getLastIndexOf(row.SUB_TABLE_NAME) == "F") {  //F 进入件详情
            this.jianDetailsOpen = true;
          } else { //进入卷详情 和项目详情
            this.juanDetailsOpen = true
          }
        })
      })
    },
    //隐藏展开箭头
    getRowClass(row) {
      if (row.row.children1 === undefined) {
        return 'row-expand-cover';
      }
      if (row.row.children1.children2 === undefined) {
        return 'row-expand-cover';
      }
    },
    chanageStatus(row) {
      if (this.flag) {
        this.flag = false
        var form = {
          processId: this.processId,
          archiveId: row.ID,
          status: row.archiveAgreeStatus
        }
        setArchiveProcessStatusByArchiveId(form).then(response => {
          this.init(this.info)
          this.flag = true
          this.form.resource = 2;
          this.$forceUpdate();
        })
      } else {
        this.$message({ message: '重复点击，请稍后再试!', type: 'warning' })
      }
    },
    // 下载操作触发
    handleCommand(command) {
      if (this.form.submitUserId == undefined || this.form.submitUserId == null || this.form.submitUserId == "") {
        this.$modal.msgError("申请人不能为空");
        return;
      } else if (this.form.submitDeptId == undefined || this.form.submitDeptId == null || this.form.submitDeptId == "") {
        this.$modal.msgError("归属部门不能为空");
        return;
      } else if (this.tableDataList.length == 0) {
        this.$modal.msgError("档案数据不能为空");
        return;
      }
      switch (command) {
        case "archiveTransfer":
          this.archiveTransfer();
          break;
        case "photoHandover":
          this.photoHandover();
          break;
        case "projectHandover":
          this.projectHandover();
          break;
        default:
          break;
      }
    },
    // 审计档案移交清单
    archiveTransfer() {
      this.form.categoryIdaf = 'sj';
      downloadDocx(this.form).then((res) => {
        // 创建一个 Blob 对象，用于存储二进制数据
        if (res.data.result == "fail") {
          this.$message({ message: res.data.msg, type: 'warning' })
        } else {
          window.open(res.data.url);
        }
      });
    },
    // 照片及录音录像移交清单
    photoHandover() {
      this.form.categoryIdaf = 'zp';
      downloadDocx(this.form).then((res) => {
        // 创建一个 Blob 对象，用于存储二进制数据
        if (res.data.result == "fail") {
          this.$message({ message: res.data.msg, type: 'warning' })
        } else {
          window.open(res.data.url);
        }
      });
    },
    // 工程档案移交清单
    projectHandover() {
      this.form.categoryIdaf = 'kj';
      downloadDocx(this.form).then((res) => {
        // 创建一个 Blob 对象，用于存储二进制数据
        if (res.data.result == "fail") {
          this.$message({ message: res.data.msg, type: 'warning' })
        } else {
          window.open(res.data.url);
        }
      });
    }
  }
}
</script>
<style lang="scss" scoped>
h2 {
  display: block;
  text-align: center;
  line-height: 30px;
  font-size: 30px;
  font-weight: bold;
}

.j_content {
  display: flex;
  flex-direction: row;
  justify-content: center;
}

.margin_top {
  margin-top: 20px
}

::v-deep .input-border input {
  border: 0 !important;
}

.tableData {
  overflow-y: auto;
  width: 90%;
  margin: 20px auto 0;
}</style>
